<template>
  <div class="purchase-return-entry">
    <div class="date-range-search">
      <el-form :inline="true" class="search-form">
        <el-form-item label="单据号：">
          <el-input
            v-model="select.searchQuery"
            placeholder="请输入单据号"
          ></el-input>
        </el-form-item>

        <el-form-item label="供应商">
          <el-input style="width: 150px" v-model="proName"></el-input>
          <el-button style="margin: 0px" @click="dialogShow = true"
            >...</el-button
          >
        </el-form-item>

        <el-form-item label="单据日期:">
          <el-date-picker
            type="daterange"
            v-model="DjDateRange"
            align="right"
            unlink-panels
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateChange2"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="付款状态:">
          <el-select
            v-model="select.paymentStatus"
            multiple
            style="width: 300px"
            placeholder="请选择"
          >
            <el-option label="未付款" value="1"></el-option>
            <el-option label="部分付款" value="2"></el-option>
            <el-option label="全部付款" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="审核状态:">
          <el-select v-model="select.reviewStatus" placeholder="请选择">
            <el-option label="空" value=""></el-option>
            <el-option label="保存" value="0"></el-option>
            <el-option label="提交" value="1"></el-option>
            <el-option label="审核" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="退货状态:">
          <el-select
            v-model="select.returnStatus"
            multiple
            style="width: 300px"
            placeholder="请选择"
          >
            <el-option label="未退货" value="1"></el-option>
            <el-option label="部分退货" value="2"></el-option>
            <el-option label="全部退货" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="仓库:">
          <el-select v-model="select.wId" placeholder="请选择">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="item in storeHouse"
              :key="item.shId"
              :label="item.storeHomeCode + ' ' + item.storeHomeName"
              :value="item.shId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品:">
          <el-input
            v-model="select.goodcode"
            placeholder="请选择商品"
          ></el-input>
        </el-form-item>
        <el-button style="margin-left: -10px" @click="goodsShow = true"
          >...</el-button
        >
        <el-form-item>
          <el-button type="primary" @click="selectPage(1, 100)">查询</el-button>
          <!-- <el-button @click="advancedSearch">高级搜索</el-button> -->
        </el-form-item>
      </el-form>
    </div>

    <el-divider></el-divider>

    <div class="actions">
      <el-button type="primary" @click="goto('PurchaseOrder')">新增</el-button>
      <!-- <el-button type="success">审核</el-button>
      <el-button type="warning">反审核</el-button> -->
      &nbsp;
            <el-upload
        style="display: inline-block"
        class="upload-demo"
        action="/purchase/read/purchase"
        :on-success="isOk"
      >
        <el-button type="primary">导入</el-button>
      </el-upload>&nbsp;
      <el-button type="primary" @click="exportData()">导出</el-button>
      <el-button type="primary">启用</el-button>
      <el-button type="warning">关闭</el-button>
      <!-- <el-button type="danger">删除</el-button> -->
    </div>

    <el-table
      :data="pageInfo ? pageInfo.list : []"
      border
      style="width: 100%; font-size: 13px; margin-left: 20px"
      show-summary
      height="310px"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="操作" width="55">
        <template slot-scope="scope">
          <i class="el-icon-edit" @click="up(scope.row)"></i>&nbsp;
          <i class="el-icon-delete" @click="delPurOrd(scope.row.id)"></i>
        </template>
      </el-table-column>
      <el-table-column prop="createDate" label="单据日期" width="200">
      </el-table-column>
      <el-table-column prop="documentNumber" label="单据编号" width="200">
      </el-table-column>
      <el-table-column prop="proName" label="供应商" width="250">
      </el-table-column>
      <el-table-column prop="yName" label="业务员"> </el-table-column>
      <el-table-column
        prop="returnOrderNumber"
        width="350"
        label="关联购货退货单号"
      >
      </el-table-column>
      <el-table-column prop="orderNumber" width="350" label="关联购货订单号">
      </el-table-column>
      <el-table-column prop="quantity" label="数量"> </el-table-column>
      <el-table-column prop="amount" label="购货金额"> </el-table-column>

      <el-table-column prop="writtenOffAmount" label="已付款">
      </el-table-column>

      <el-table-column label="付款状态">
        <template slot-scope="scope">
          <div v-if="scope.row.writtenOffAmount == 0">未付款</div>
          <div v-else-if="scope.row.writtenOffAmount === scope.row.amount">
            全部付款
          </div>
          <div v-else>部分付款</div>
        </template>
      </el-table-column>

      <el-table-column prop="returntype" label="退货状态">
        <template slot-scope="scope">
          <div v-if="scope.row.returnQuantity == 0">未退货</div>
          <div v-else-if="scope.row.returnQuantity === scope.row.quantity">
            全部退货
          </div>
          <div v-else>部分退货</div>
        </template>
      </el-table-column>
      <el-table-column prop="singleName" label="制单人"> </el-table-column>
      <el-table-column prop="dateOrder" label="制单时间" width="200">
      </el-table-column>

      <el-table-column prop="purPriSum" label="采购费用"> </el-table-column>

      <el-table-column prop="reviewStatus" label="审核状态">
        <template slot-scope="scope">
          <div v-if="scope.row.reviewStatus == 0">保存</div>
          <div v-if="scope.row.reviewStatus == 1">提交</div>
          <div v-else-if="scope.row.reviewStatus == 2">审核</div>
        </template>
      </el-table-column>
      <el-table-column prop="reviewName" width="150" label="最后审核人">
      </el-table-column>

      <el-table-column prop="remark" label="备注"> </el-table-column>
      <el-table-column prop="deliveryMethodId" label="交货方式">
        <template slot-scope="scope">
          <div v-if="scope.row.deliveryMethodId === 1">快递物流</div>
          <div v-else-if="scope.row.deliveryMethodId === 2">自配送</div>
          <div v-else-if="scope.row.deliveryMethodId === 3">自提</div>
          <div v-else-if="scope.row.deliveryMethodId === 4">其它</div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-left: 500px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageInfo ? pageInfo.pageNum : 1"
      :page-sizes="[100, 200, 300, 400]"
      :page-size="pageInfo ? pageInfo.pageSize : 100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo ? pageInfo.total : 0"
    >
    </el-pagination>

    <el-dialog top="20px" title="选择商品" :visible.sync="goodsShow">
      <GoodsChoose ref="chooseGoods" :goodsShow="goodsShow" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="goodsShow = false">取 消</el-button>
        <el-button type="primary" @click="yesGoods">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog top="20px" title="选择供应商" :visible.sync="dialogShow">
      <ProviderChoose ref="choosePro" :dialogShow="dialogShow" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">取 消</el-button>
        <el-button type="primary" @click="yes">确 定</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import GoodsChoose from "../public_com/GoodsChoose.vue";
import ProviderChoose from "../public_com/ProviderChoose.vue";

export default {
  name: "purOrdDoc",
  components: {
    GoodsChoose,
    ProviderChoose,
  },
  data() {
    return {
      proName: "",
      DjDateRange: [],
      dialogShow: false,
      goodsShow: false,
      storeHouse: [],
      pageInfo: [],
      select: {
        wId: "",
        searchQuery: "",
        startDate2: "",
        endDate2: "",
        goodcode: "",
        proId: "",
        paymentStatus: [],
        reviewStatus: [],
        purType:1,
      },
    };
  },
  methods: {
    generateRandomNumber() {
      return Math.floor(100000 + Math.random() * 900000); // 生成范围在 100000 到 999999 之间的随机数
    },
    exportData() {
      var multipleSelection = [];
      multipleSelection = this.pageInfo.list;
      // if (
      //   this.multipleSelection != null &&
      //   this.multipleSelection.length != 0
      // ) {
      //   console.log("now", this.multipleSelection);
      //   multipleSelection = this.multipleSelection;
      // }

      fetch("/purchase/export/purchase", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(multipleSelection),
      })
        .then((response) => {
          if (!response.ok) {
            throw new Error("响应出错");
          }
          return response.blob();
        })
        .then((blob) => {
          // 生成下载链接并下载文件
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          var name = this.generateRandomNumber();
          a.download = "购货单_" + name + ".xlsx"; // 设置下载的文件名
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
        })
        .catch((error) => {
          console.error("下载文件时出错:", error);
        });
    },

    delPurOrd(id) {
      this.$confirm("删除该条购货单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios
            .get("/purchase/purchaseOrder/delete", {
              params: {
                id,
              },
            })
            .then((rs) => {
              if (rs.data.code == 200) {
                this.successMessage("删除成功");
                this.selectPage(1, 100);
              } else {
                this.errorMessage("删除出错了");
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSizeChange(newSize) {
      console.log(`每页 ${newSize} 条`);
      this.findAll(1, newSize);
    },
    handleCurrentChange(newPage) {
      console.log(`当前页: ${newPage}`);
      this.findAll(newPage, this.pageInfo.pageSize);
    },
    up: function (row) {
      this.$router.push({ name: "PurchaseOrder", query: { id: row.id } });
    },
    goto(to) {
      this.$router.push(to);
    },
    handleDateChange2(value) {
      if (value) {
        this.select.startDate2 = value[0]; // 起始日期
        this.select.endDate2 = value[1]; // 结束日期
      } else {
        this.select.startDate2 = ""; // 起始日期
        this.select.endDate2 = ""; // 结束日期
      }
    },
    yes() {
      this.dialogShow = false;
      var list = this.$refs.choosePro.selectionList;
      if (list.length <= 0) {
        this.proName = "";
        this.select.proId = "";
        return;
      }
      this.proName = list[0].providerName;
      this.select.proId = list[0].providerId;
    },
    yesGoods() {
      this.goodsShow = false;
      var selectedGoods = this.$refs.chooseGoods.selectionList;
      console.log(selectedGoods);
      if (selectedGoods.length <= 0) {
        this.select.goodcode = "";
        return;
      }
      if (selectedGoods.length > 0) {
        this.select.goodcode = selectedGoods[0].goodcode;
      }
    },
    successMessage(msg) {
      this.$message({
        message: msg,
        type: "success",
      });
    },
    errorMessage(msg) {
      this.$message({
        message: msg,
        type: "error",
      });
    },
    selectPage(pageNum, pageSize) {
      console.log(this.select);



      this.axios
        .get("/purchase/purchaseOrder/getPage", {
          params: {
            pageNum,
            pageSize,
            ...this.select,
          },
          paramsSerializer: function (params) {
            return new URLSearchParams(params).toString();
          },
        })
        .then((rs) => {
          console.log(rs);
          if (rs.data.pageInfo) {
            this.pageInfo = rs.data.pageInfo;
          }
        });


    },
    selctSH() {
      this.axios
        .get("/info/storeHouse/getAllStore", {
          params: {
            cId: 1,
          },
        })
        .then((rs) => {
          this.storeHouse = rs.data.storeList;
        });
    },
  },
  created() {
    this.selctSH();
    this.selectPage(1, 100);
  },
};
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}

.actions {
  margin-top: 20px;
  text-align: right;
  margin-bottom: 10px;
}

.search-form .el-button {
  margin-left: 10px;
}
</style>
